﻿#include"SocketHelper.h"

int SocktetUtil::initSocket(){
    // 加载套接字库
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;
    wVersionRequested = MAKEWORD(1, 1);
    // 初始化套接字库
    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0)
    {
        return err;
    }
    if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
    {
        WSACleanup();
        return -1;
    }
    return 0;
}
SOCKET SocktetUtil::openListen(int port, int backlog) {
    // 新建套接字
    SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0);
    // 初始化地址信息
    SOCKADDR_IN addrSrv;
    addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    addrSrv.sin_family = AF_INET;
    addrSrv.sin_port = htons(port);
    //将socket绑定到本机port端口
    if (bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)) == SOCKET_ERROR) {
        closesocket(sockSrv);
    }
    //开启监听
    if (listen(sockSrv, backlog) == SOCKET_ERROR) {
        closesocket(sockSrv);
    }
    return sockSrv;
}
//客户端获取套接字
SOCKET SocktetUtil::openClientSocket(const char* ip,int port) {
    // 创建套接字
    SOCKET sockCli = socket(AF_INET, SOCK_STREAM, 0);
    // 初始化服务端地址
    SOCKADDR_IN addrSrv;
    addrSrv.sin_addr.S_un.S_addr = inet_addr(ip);
    addrSrv.sin_family = AF_INET;
    addrSrv.sin_port = htons(port);
    //向服务器发起连接请求
    if (connect(sockCli, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)) == SOCKET_ERROR) {
        closesocket(sockCli);
        return sockCli;
    }
    return sockCli;
}
